package com.cdxzwk.serial;
import android.util.Log;
import com.cdxzwk.serial.listener.OnOpenSerialPortListener;
import com.cdxzwk.serial.listener.OnSerialPortDataListener;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class SerialPortHelper {
    /**
     * 直接初始化静态变量，确保线程安全
     */
    private static final SerialPortHelper mInstance = new SerialPortHelper();

    /**
     * 串口工具
     */
    private SerialPortManager serialPortManager;
    private SerialPortFinder serialPortFinder;
    List<String> allDevices = new ArrayList<>();

    public static SerialPortHelper getInstance() {
        return mInstance;
    }

    public List<String> getAllDevices() {
        if (allDevices.size() != 0) allDevices.clear();
        if (serialPortFinder == null) serialPortFinder = new SerialPortFinder();
        String[] entryValues = serialPortFinder.getAllDevicesPath();
        allDevices.addAll(Arrays.asList(entryValues));
        return allDevices;
    }

    /**
     * @param device   串口
     * @param baudRate 波特率
     */
    public void open(File device, int baudRate, OnOpenSerialPortListener onOpenSerialPortListener) {
        serialPortManager = new SerialPortManager(device, baudRate, onOpenSerialPortListener);
    }

    /**
     * @param onSerialPortDataListener 数据返回监听
     */
    public void setOnSerialPortDataListener(OnSerialPortDataListener onSerialPortDataListener) {
        serialPortManager.setOnSerialPortDataListener(onSerialPortDataListener);
    }

    /**
     * @param hex 要发送的hex
     */
    public boolean sendHex(String hex) {
//        if (serialPortManager == null)
//            throw new SecurityException("====请先初始化串口=======");
        if (serialPortManager == null)
            return false;
        return serialPortManager.sendHex(hex);
    }

    /**
     * @param txt 要发送的txt
     */
    public boolean sendTxt(String txt) {
//        if (serialPortManager == null)
//            throw new SecurityException("====请先初始化串口=======");
        if (serialPortManager == null)
            return false;
        return serialPortManager.sendTxt("");
    }

    /**
     * 关闭串口，一般在onDestory中调用
     */
    public boolean close() {
//        if (serialPortManager == null)
//            throw new SecurityException("====请先打开串口=======");
        if (serialPortManager == null)
            return false;
        serialPortManager.closeSerialPort();
        return true;
    }

    /**
     * 关闭监听线程
     */
    public boolean stopThread() {
//        if (serialPortManager == null)
//            throw new SecurityException("====请先打开串口=======");
        if (serialPortManager == null)
            return false;
        Log.e("监听", "已经停止");
        // 停止发送消息的线程
        serialPortManager.stopSendThread();
        // 停止接收消息的线程
        serialPortManager.stopReadThread();
        return true;
    }
}
